package com.wm.blog_common.util;

import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/***
 * @ClassName: RegexUitl
 * @Description: 正则工具类
 * @Author: wm_yu
 * @Create_time: 16:30 2020-3-27
 */
public class RegexUitl {

    private RegexUitl(){}
    /**
     * 正则匹配,全部匹配,返回布尔值
     * @param source
     * @param regex
     * @return
     */
    public static Boolean check(String source,String regex){
        Boolean isOk = false;
        if(StringUtils.isNotEmpty(source)){
            Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
            Matcher matcher = pattern.matcher(source);
            if(matcher.matches()){
                isOk = true;
            }
        }
        return isOk;
    }
    /**
     * 匹配字符串,得到第一个匹配,指定需要获取的组
     * @param source
     * @param regex
     * @param group
     * @return
     */
    public static String match(String source,String regex,int group){
        String result = null;
        if(StringUtils.isNotEmpty(source)){
            Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
            Matcher matcher = pattern.matcher(source);
            if (matcher.find()){
                return matcher.group(group).trim();
            }
        }
        return result;
    }


    /**
     * 匹配字符串,得到第一个匹配,指定需要获取的组
     * @param source
     * @param regex
     * @param group
     * @param limit 现在返回的长度
     * @return
     */
    public static List<String> matchList(String source,String regex,int group,int limit){
        List<String> list = new ArrayList<>();
        if(StringUtils.isNotEmpty(source)){
            Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
            Matcher matcher = pattern.matcher(source);
            int i = 0;
            while(matcher.find() && i < limit){
                String trim = matcher.group(group).trim();
                list.add(trim);
                i ++;
            }
        }
        return list;
    }

}
